/*
 * @Author: YinJianFeng 814922893@qq.com
 * @Date: 2025-01-23 15:49:07
 * @LastEditors: YinJianFeng 814922893@qq.com
 * @LastEditTime: 2025-01-23 17:35:13
 */
import { Button, Popover, Tooltip } from 'antd';
import styles from './styles.module.scss';
import {
  CaretRightOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
} from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { useWidgetStore } from '@/common/store';
import { Icon } from '@amcax/base';
import { LeftPanelMenu, ILeftMenuItem } from '@/layouts/LeftPanels';
import { i18n } from '@/common/utils';
import { widgetManager } from '@/common/managers/widgetManager';
import { ReactComponent as IconMenu } from './icons/menu.svg';
import { ReactComponent as IconPin } from './icons/icon_pin.svg';
import { ReactComponent as IconUnpin } from './icons/icon_unpin.svg';

interface IProps {
  onCollapse?: (collapsed: boolean) => void;
  onSelect?: (id: string) => void;
}

// const fixed = 'commands/leftPanel/guding';
// const unfixed = 'commands/leftPanel/weiguding';
// const menus = 'commands/leftPanel/caidanguanli';
const className_li = `h-[35px] w-full flex flex-col justify-center items-center relative`;

export default function LeftNavigator({ onCollapse, onSelect }: IProps) {
  const { leftPanel, hisSelection, selectId, modalId } = useWidgetStore();
  const [collapsed, setCollapsed] = useState(false);
  const [popoverOpen, setPopoverOpen] = useState(false);
  const handleCollapse = () => {
    setCollapsed(!collapsed);
    onCollapse(!collapsed);
  };

  const handleSelect = (item: ILeftMenuItem) => {
    onSelect?.(item.id);
    if (item.type !== 'modal') {
      widgetManager.updataHisSelection(updata(hisSelection, item.id, true));
      widgetManager.setSelectId(item.id);
    } else {
      widgetManager.setModalId(item.id);
    }
    setPopoverOpen(false);
  };

  // const openMenuList = () => {
  //   setPopoverOpen(!popoverOpen);
  // };
  const getIcon = (name, id?: string, hoverShow = false) => (
    <Icon
      className={`${hoverShow && styles.icon}`}
      name={name}
      style={{
        fontSize: '20px',
      }}
      onClick={(e) => {
        if (!id) {
          return;
        }
        widgetManager.leftPanelUpdata(updata(leftPanel, id));
        e.preventDefault();
      }}
    />
  );
  const updata = (data: string[], id: string, isAdd = false) => {
    const menuIds = new Set(data);
    menuIds.has(id) ? !isAdd && menuIds.delete(id) : menuIds.add(id);
    return [...menuIds];
  };
  useEffect(() => {
    const defaultFocus = LeftPanelMenu.find((item) => item.focus);
    defaultFocus && handleSelect(defaultFocus);
  }, []);

  // const content = (
  //   <div className={styles.menuList}>
  //     {LeftPanelMenu.map((item, index) => {
  //       const isFixed = leftPanel.includes(item.id);
  //       return (
  //         <TooltipCom
  //           key={index}
  //           item={item}
  //           delay={1}>
  //           <Flex className={`${styles.liItem}`}>
  //             {getIcon(item.icon)}
  //             <span
  //               onClick={() => handleSelect(item)}
  //               style={{
  //                 flex: 1,
  //                 padding: '2px 4px',
  //                 alignItems: 'center',
  //                 width: '250px',
  //               }}>
  //               {i18n.t(item.label)}
  //             </span>
  //             {getIcon(isFixed ? fixed : unfixed, item.id, !isFixed)}
  //           </Flex>
  //         </TooltipCom>
  //       );
  //     })}
  //   </div>
  // );

  const MenuList = () =>
    LeftPanelMenu.map((item, index) => {
      const isFixed = leftPanel.includes(item.id);
      return (
        <div
          className='flex flex-row justify-between items-center w-[200px] gap-2 px-3 py-1 group hover:bg-gray-100'
          key={index}>
          <div>{getIcon(item.icon)}</div>
          <div
            className='flex-1 cursor-pointer'
            onClick={() => handleSelect(item)}>
            {i18n.t(item.label)}
          </div>
          <div className={`${!isFixed && 'hidden group-hover:!block'}`}>
            <div
              className='border border-gray-400 w-[20px] h-[20px] flex justify-center items-center rounded-sm bg-gray-100'
              onClick={(e) => {
                widgetManager.leftPanelUpdata(updata(leftPanel, item.id));
                e.preventDefault();
              }}>
              {isFixed ? (
                <IconPin
                  width='15px'
                  height='15px'
                  className='w-[15px]'
                />
              ) : (
                <IconUnpin className='w-[15px]' />
              )}
            </div>
          </div>
        </div>
      );
    });

  return (
    <div className={styles.leftNavigator}>
      <ul className='w-full h-screen'>
        <Popover
          open={popoverOpen}
          classNames={{ root: styles.popover }}
          arrow={false}
          content={MenuList}
          placement='rightTop'
          onOpenChange={(open) => setPopoverOpen(open)}
          getPopupContainer={() =>
            document.getElementById('app-nextshape_root')
          }
          trigger='click'>
          {/* <li
            key={'menu-list'}
            className={className_li}
            onClick={() => openMenuList()}>
            {getIcon(menus)}
          </li> */}
          <div className='h-[35px] w-full flex flex-col justify-center items-center relative bg-transparent'>
            <Button
              className='w-full h-full border-none border-transparent bg-transparent shadow-none'
              size='small'
              icon={<IconMenu className='w-[20px]' />}></Button>
            <CaretRightOutlined
              className='absolute right-0 bottom-0 text-[10px]'
              rotate={45}
            />
          </div>
        </Popover>
        {LeftPanelMenu.map(
          (item, index) =>
            (leftPanel.includes(item.id) ||
              hisSelection.includes(item.id) ||
              modalId === item.id) && (
              <TooltipCom
                key={index}
                item={item}
                delay={1}>
                <li
                  key={item.id}
                  className={`
                ${className_li}
                ${selectId === item.id || modalId === item.id ? 'bg-white ' : ''}
                ${hisSelection.includes(item.id) ? styles.li : ''}
              `}
                  onClick={() => handleSelect(item)}>
                  {getIcon(item.icon)}
                </li>
              </TooltipCom>
            ),
        )}
      </ul>
      <Button
        className={styles.leftNavigatorButton}
        icon={collapsed ? <DoubleRightOutlined /> : <DoubleLeftOutlined />}
        onClick={handleCollapse}></Button>
    </div>
  );
}

function TooltipCom({ item, children, delay }) {
  return (
    <Tooltip
      color={'#fff'}
      arrow={false}
      placement='bottom'
      mouseEnterDelay={delay}
      title={
        <div className={styles.tooltip}>
          {item?.describe || i18n.t(item.label)}
        </div>
      }>
      {children}
    </Tooltip>
  );
}
